import { ref, getCurrentInstance } from 'vue'
import type { LabelData } from '@/utils/interface'
import { useUserStore } from '@/stores/user'
import { useCode } from '@/hooks/code'
import { addLabelAPI, labelAPI, deleteLabelAPI } from '@/api'

const userStore = useUserStore()
const { tackleCode } = useCode()

export function useLabel() {
  // 新建分组内容
  const inputValue = ref<string>()

  // 获取标签
  const label = ref<LabelData[]>([])
  // 获取标签
  const rawLabel = async () => {
    const request = {
      token: userStore.token,
    }
    const res: any = await labelAPI(request)
    if (tackleCode(res.code)) {
      console.log(res)
      label.value = [...res.data]
    }
  }

  const proxy: any = getCurrentInstance()?.proxy
  // 取消
  function cancel() {
    inputValue.value = ''
  }

  async function confirm() {
    if (inputValue.value) {
      const request = {
        token: userStore.token,
        value: {
          moment: new Date(),
          label_name: inputValue.value,
        },
      }

      const res: any = await addLabelAPI(request)
      if (tackleCode(res.code)) {
        const lab = {
          id: res.data,
          label_name: inputValue.value!,
        }
        label.value.unshift(lab)
        inputValue.value = ''
        proxy.$message({ type: 'primary', message: '插入成功' })
      }
      // subsetStore.data.push(obj)
    } else {
      proxy.$message({ type: 'error', message: '插入失败' })
    }
  }

  // 管理分组
  const visible = ref<boolean>(false)
  const showModal = () => {
    visible.value = true
  }

  // 删除标签
  const deleteLabel = async (e: number | string) => {
    // 提交后端处理
    const request = {
      token: userStore.token,
      labelId: e,
    }
    const res: any = await deleteLabelAPI(request)
    if (tackleCode(res.code)) {
      label.value = label.value.filter((obj: { id: number | string }) => {
        return obj.id !== e
      })
      proxy.$message({ type: 'primary', message: '删除成功' })
    }
  }

  return {
    inputValue,
    label,
    rawLabel,
    cancel,
    confirm,
    visible,
    showModal,
    deleteLabel,
  }
}
